#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QTextCodec>
#include <QFontDatabase>
#include <QFontDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("USB管理系统");

    QFont font = QFont("Song Ti");

    for(int i = 0; i < MAX_USB_COUNT; i++){
        QImage img(UNCONNECT_USB_PNG_PATH);
        QLabel *label = new QLabel(ui->centralWidget);  //创建QLabel控件
        label->setPixmap(QPixmap::fromImage(img));
        label->setObjectName(QString::number(i,10)+"-img");
        label->setScaledContents(true);
        label->show();

        QLabel *label_text = new QLabel(ui->centralWidget);  //创建QLabel控件
        label_text->setFont(font);
        label_text->setText("0000000000000000000000000");
        label_text->setObjectName(QString::number(i,10)+"-serial");
        label_text->setScaledContents(true);
        label_text->show();
    }

    resizeWindow();

    mUSBThread = new USBThread(this);
    mUSBThread->start();
    mUSBManagementThread = new USBManagementThread(this);
    connect(mUSBManagementThread, SIGNAL(ChangeWindowSignal(sUSB *)), this, SLOT(ChangeWindow(sUSB *)));
    mUSBManagementThread->start();
    setUSBManageRunCount(2);

}

void MainWindow::resizeWindow(){
    int width = geometry().width();
    int height = geometry().height();

    int usb_size = qMin(width / 10, height / (MAX_USB_COUNT));
    for(int i = 0; i < MAX_USB_COUNT; i++){
        QLabel *label = ui->centralWidget->findChild<QLabel*>(QString::number(i,10)+"-img");
        label->move((i % 2) * (width / 2) + usb_size / 2,usb_size / 2 + (i / 2) * (usb_size * 1.5));
        label->resize(usb_size,usb_size);

        QLabel *label_text = ui->centralWidget->findChild<QLabel*>(QString::number(i,10)+"-serial");
        label_text->move((i % 2) * (width / 2) + usb_size * 1.5,usb_size / 2 + (i / 2) * (usb_size * 1.5));

    }
}

void MainWindow::resizeEvent (QResizeEvent * event){
    resizeWindow();
}

MainWindow::~MainWindow()
{
    delete ui;
    //mUSBThread->setIsRun(false);
    //mUSBThread->wait();
}

void MainWindow::setUSBManageRunCount(int i){
    mUSBManagementThread->setRunCount(i);
}

void MainWindow::ChangeWindow(sUSB *msUSB){

    QImage un_img(UNCONNECT_USB_PNG_PATH);
    QImage img(CONNECT_USB_PNG_PATH);
    for(int i = 0; i < MAX_USB_COUNT; i++){
        if(msUSB[i].is_Use == true){
            ui->centralWidget->findChild<QLabel*>(QString::number(i, 10)+"-img")->setPixmap(QPixmap::fromImage(img));
            ui->centralWidget->findChild<QLabel*>(QString::number(i, 10)+"-serial")->setText(msUSB[i].serial);
        }
        else{
            ui->centralWidget->findChild<QLabel*>(QString::number(i, 10)+"-img")->setPixmap(QPixmap::fromImage(un_img));
            ui->centralWidget->findChild<QLabel*>(QString::number(i, 10)+"-serial")->setText("拔出");
        }
    }
}
